package com.fahai.web.controller;/**
 * Created by Lilinjun on 17/6/27.
 */

import com.fahai.common.PageVo;
import com.fahai.utils.CommonUtil;
import com.fahai.utils.DateUtil;
import com.fahai.utils.json.JsonResult;
import com.fahai.web.entity.Anyuan;
import com.fahai.web.entity.DataAnalyse;
import com.fahai.web.service.SourceService;
import com.fahai.web.vo.DataAnalyseQueryVO;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 案源管理
 *
 * @author
 * @create 2017-06-27 下午3:31
 **/
@Controller
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequestMapping(value = "/source")
public class SourceController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(MarketController.class);
    @Autowired
    private SourceService sourceService;

    /**
     * 跳转到查询页面
     *
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','案源管理-0','案源管理-1')")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String anyuanList(Model model) {
        model.addAttribute("selectTab", "案源管理");
        return "source_manage";
    }

    /**
     * 查询
     *
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','案源管理-0','案源管理-1')")
    @ResponseBody
    @RequestMapping(value = "/queryAnyuan", method = RequestMethod.POST)
    public JsonResult queryAnYuan(PageVo pageVo, Model model, Anyuan anyuan) {
        pageVo = sourceService.selectSourceList(anyuan, pageVo);
        //pageVo.setTotal(Long.valueOf(sourceService.getCount(anyuan)));
        model.addAttribute("selectTab", "案源管理");
        return ok("查询", pageVo);
    }

    /**
     * 查询
     *
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','案源管理-0','案源管理-1')")
    @ResponseBody
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public JsonResult count(PageVo pageVo, Model model, Anyuan anyuan) {
        int total = sourceService.getCount(anyuan);
        pageVo.setTotal(Long.valueOf(total));
        return ok("查询", pageVo);
    }

    /**
     * 更新
     *
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','案源管理-0','案源管理-1')")
    @ResponseBody
    @RequestMapping(value = "/updateAnyuan", method = RequestMethod.POST)
    public JsonResult updateAnYuan(Anyuan anyuan) {
        sourceService.updateAnyuan(anyuan);
        return ok("修改成功");
    }

    /**
     * 更新
     *
     * @param
     * @return
     */
    @PreAuthorize("hasAnyAuthority('ADMIN','案源管理-0','案源管理-1')")
    @RequestMapping(value = "/batchFreeze", method = RequestMethod.POST)
    public JsonResult batchFreeze(@RequestParam(required = false, value = "list[]") List<String> list, String freezeType) {
        List<Integer> idlist = new ArrayList<Integer>();
        for (String id : list
                ) {
            idlist.add(Integer.valueOf(id));
        }
        sourceService.freeze(idlist,freezeType);
        return ok("修改成功");
    }




    /**
     * 导出xls
     * @param response
     * @param request
     */
    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, HttpServletRequest request) {
        String[] headers = new String[]{"客户ID", "客户姓名/昵称", "客户手机号", "客户手机号归属地", "当前捆绑律师", "首次咨询时间",
                "末次咨询时间", "客户创建时间", "通话时长", "通话结果", "咨询有效性", "咨询发起方", "咨询发起时刻",
                "服务律师ID", "服务律师姓名", "服务律师电话", "服务律师状态", "服务律师地区"};
        Anyuan vo = new Anyuan();
        vo.setUname(request.getParameter("uname"));//客户名称
        vo.setUphone(request.getParameter("uphone"));//客户电话

        PageVo pageVo= new  PageVo();


        try {
            expExcel(request, response, vo);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     *
     * @param request
     * @param resp
     * @param anyuan
     * @throws IOException
     */
    public   void expExcel(HttpServletRequest request, HttpServletResponse resp, Anyuan anyuan) throws IOException {

        PageVo pageVo= new PageVo();
        List<Anyuan> vos_call =sourceService.selectSourceListxls(anyuan);
        HSSFWorkbook wb = new HSSFWorkbook();
        request.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/x-download");
        String fileName = "数据分析"+System.currentTimeMillis()+".xls";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        String[] headers={"用户Id","用户姓名","用户电话","用户注册时间","用户归属地","用户余额","律师Id","律师姓名","律师电话","律师余额","律师服务地","律师来源","雇佣类型","律师状态","咨询发起时间","首次咨询时间","通话时长","通话结果","咨询有效性","发起方","咨询发起位置"};
        HSSFSheet sheet = wb.createSheet("数据分析");
        sheet.setDefaultRowHeight((short) (2 * 256));
        //sheet.setColumnWidth(0, 50 * 160);
        HSSFCellStyle cellStyle = wb.createCellStyle();
        HSSFCellStyle cellStyle_content = wb.createCellStyle();

        HSSFRow row =sheet.createRow(0);
        HSSFFont headerFont = wb.createFont(); // 创建字体样式
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        headerFont.setFontName("宋体"); // 设置字体类型
        //headerFont.setColor(HSSFFont.COLOR_RED);
        headerFont.setFontHeightInPoints((short) 14); // 设置字体大小
        cellStyle.setFont(headerFont); // 为标题样式设置字体样式
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中


        for (int i=0;i<headers.length;i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(cellStyle);
        }

        HSSFFont font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 14);
        int rowCount=0;
        if(null!=vos_call&&vos_call.size()>0){
            for (int i = 0; i < vos_call.size(); i++)
            {
                HSSFRow row1 = sheet.createRow((int) i + 1);
                rowCount++;
                //row1.setRowStyle(cellStyle);
                Anyuan vo = vos_call.get(i);
                int j=0;
                //row1.createCell(j++).setCellValue(i + 1);
                HSSFCell cell;
                cellStyle_content.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 水平方向的对齐方式
                row1.createCell(j++).setCellValue(String.valueOf(vo.getUserid()==null?"":vo.getUserid()));//客户ID
                row1.createCell(j++).setCellValue(String.valueOf(vo.getUname()==null?"":vo.getUname()));//客户姓名/昵称
                row1.createCell(j++).setCellValue(String.valueOf(vo.getUphone()==null?"":vo.getUphone()));//用户手机号

                //用户余额
                cell= row1.createCell(j++);
                cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                cell.setCellStyle(cellStyle_content);

                row1.createCell(j++).setCellValue("");//TODO 律师来源
                row1.createCell(j++).setCellValue("");//TODO 雇佣类型


                 //通话时长
                cell=row1.createCell(j++);
                cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                cell.setCellStyle(cellStyle_content);

            }
        }









        OutputStream out = resp.getOutputStream();
        wb.write(out);
        out.close();
    }

}
